import { useEffect, useState, useImperativeHandle, forwardRef, useRef } from 'react';
import { Input, Button, Menu, message, Dropdown } from 'antd';
import BizBody from '@inbiz/basic/BizBody';
import { InbizIcon, useEvents, getEditor } from '@inbiz/utils';
import MemberSelect from '@inbiz/basic/MemberSelect';
import PlusSign from './components/PlusSign';
import WithDrawModal from './components/WithDrawModal';
import TerminateModal from './components/TerminateModal';
import AutoInput from './components/AutoInput';
import { TextWidget, getMessage } from '@inbiz/react';
import { filterBtns } from '../commonUtils';
import extendsApi from '../api';
import { handleClick } from '../OutFunction';
import { useDraft, useUrgeAndWithDraw } from '../useHooks';
import type { ProcessButtonProps, ButtonStructure } from './types';
import { getTaskState, assignTask } from './service';
import './style.less';

const { TextArea } = Input;

const App = forwardRef((props: ProcessButtonProps, ref) => {
  const batchApproval = sessionStorage.getItem('batchApproval');
  const { webbuttonConfig, inbiz, buttonVisible, tips, showCCmember, showComment } = props;
  const processvars = useRef({});
  const mySummary = useRef('');
  const [hiddenButtons, $hiddenButtons] = useState(['']);
  const [opinions, $opinions] = useState('');
  const [buttons, $buttons] = useState<ButtonStructure[]>([]);
  const [selected, $selected] = useState<any[]>([]);
  const [memberSelectVisible, $memberSelectVisible] = useState(false);
  const [plusSignVisible, $plusSignVisible] = useState(false);
  const [terminateVisible, $terminateVisible] = useState(false);
  const [withDrawVisible, $withDrawVisible] = useState(false);
  const [assignVisible, setAssignVisible] = useState(false);
  const [initialTaskState, setInitialTaskState] = useState('');
  const [isNewVersionDesigner, setIsNewVersionDesigner] = useState(inbiz?.workFlow?.newAttribute === true);
  const [newActions, setNewActions] = useState(inbiz?.workFlow?.newAttribute === true ? (inbiz?.workFlow?.buttonSetting?.actions || []) : webbuttonConfig);
  const [events] = useEvents(props.callBackEvents, props.emit);
  const { userInfoByToken: userInfo, appId } = inbiz.appInfo;

  const {
    taskId,
    instanceId,
    formId,
    id,
    pageId,
    tabKey,
    drafID,
    taskState,
    IncidentState,
    processId,
  } = inbiz.queryData || {};
  const isEditor =
    getEditor() ||
    (!taskId &&
      !instanceId &&
      !formId &&
      !id &&
      !pageId &&
      !tabKey &&
      !drafID &&
      !taskState &&
      !IncidentState &&
      !processId);

  useEffect(() => {
    if (taskId && tabKey == '2') {
      getTaskState(taskId).then((res) => {
        setInitialTaskState(String(res));
      });
    }
  }, [taskId, tabKey]);

  const showDraft = useDraft({ processId, tabKey, isNewVersionDesigner });
  const { showIsUrge, showWithdraw } = useUrgeAndWithDraw({ processId, instanceId, tabKey, isNewVersionDesigner });
  // const processId = inbiz.queryData?.processId;

  useImperativeHandle(
    ref,
    () => ({
      ...extendsApi(events, mySummary, $hiddenButtons, processvars, $selected),
    }),
    [processvars, mySummary, hiddenButtons],
  );

  const operationSuccess = (res: { code: string; message: string }, type: string, item: any) => {
    let _action = typeof item == 'string' ? item : item?.action;
    events.current.onAfterSubmit?.(_action, res);
    if (res.code == '200') {
      localStorage.setItem('process-easy-view-approval-success', 'true');
      message.success(`${type}${getMessage('processButton.success')}`);
      $opinions('');
      if (tabKey == '-1') {
        let result = events.current.onBeforeClose?.(_action, res);
        if (result !== false) {
          setTimeout(() => {
            window.parent.location.reload();
          }, 500);
        }
      } else if (tabKey && tabKey != '-1') {
        let result = events.current.onBeforeClose?.(_action, res);
        if (result !== false) {
          setTimeout(() => {
            if (opener) {
              // window.opener.location.reload();
            }
            window.close();
          }, 500);
        }
      } else {
        let result = events.current.onBeforeClose?.(_action, res);
        if (result !== false) {
          setTimeout(() => {
            window.close();
          }, 500);
        }
      }
    } else {
      message.error(res.message);
    }
  };

  const handleReturnClick = (e: { key: any; }) => {
    if (isEditor) {
      return false;
    }
    const button = {
      action: '',
    };

    switch (e.key) {
      case '1':
        button.action = 'returnsBack';
        break;
      case '2':
        button.action = 'returnsStarter';
        break;
      case '3':
        button.action = 'returnsStartModify';
        break;
      default:
        break;
    }
    handleClick({
      item: button,
      events,
      inbiz,
      operationSuccess,
      selected,
      mySummary,
      taskId,
      opinions,
      props,
      instanceId,
      taskState,
      processvars,
      processId,
      $terminateVisible,
      $withDrawVisible,
      userInfo,
      id,
      formId,
      drafID,
      pageId,
    });
  };
  const returnMenu = isNewVersionDesigner ? (
    <Menu onClick={handleReturnClick}>
      <Menu.Item
        key="1"
        icon={<InbizIcon type="icon-process-tuihuishangyibu" style={{ fontSize: 26 }} />}
      >
        <TextWidget>processButton.returnPrestep</TextWidget>
      </Menu.Item>
      {
        inbiz?.workFlow?.buttonSetting?.returnsBackButtonConfig && inbiz?.workFlow?.buttonSetting?.returnsBackButtonConfig?.filter((item1) => item1?.enable === true)?.map((item) => {
          return (
            <Menu.Item
              key={item?.action == 'returnStarter' ? '2' : '3'}
              icon={<InbizIcon type={item?.action == 'returnStarter' ? 'icon-process-tuihuifaqiren' : 'icon-process-fanhuifaqirenxiugai'} style={{ fontSize: 26 }} />}
            >
              {item?.action == 'returnStarter' ? <TextWidget>processButton.returnsStarter</TextWidget> : <TextWidget>processButton.returnsStartModify</TextWidget>}
            </Menu.Item>
          )
        })
      }
    </Menu>
  ) : (
    <Menu onClick={handleReturnClick}>
      <Menu.Item
        key="1"
        icon={<InbizIcon type="icon-process-tuihuishangyibu" style={{ fontSize: 26 }} />}
      >
        <TextWidget>processButton.returnPrestep</TextWidget>
      </Menu.Item>
      {(inbiz?.workFlow && inbiz?.workFlow?.returnStarter) && (
        <Menu.Item
          key="2"
          icon={<InbizIcon type="icon-process-tuihuifaqiren" style={{ fontSize: 26 }} />}
        >
          <TextWidget>processButton.returnsStarter</TextWidget>
        </Menu.Item>
      )}
      {(inbiz?.workFlow && inbiz?.workFlow?.cdirectBack) && (
        <Menu.Item
          key="3"
          icon={<InbizIcon type="icon-process-fanhuifaqirenxiugai" style={{ fontSize: 26 }} />}
        >
          <TextWidget>processButton.returnsStartModify</TextWidget>
        </Menu.Item>
      )}
    </Menu>
  );

  useEffect(() => {
    // 编辑状态按钮不变,预览状态筛选按钮
    if (isEditor) {
      // 设计器待确定
      $buttons(isNewVersionDesigner ? newActions : webbuttonConfig);
    } else {
      const btns = filterBtns({
        isNewVersionDesigner,
        taskId,
        buttons: isNewVersionDesigner ? newActions?.filter((item: { enable: boolean; }) => item?.enable !== false) : webbuttonConfig,
        inbiz,
        tabKey,
        showDraft,
        showWithdraw,
        showIsUrge,
        hiddenButtons,
        IncidentState,
        initialTaskState,
      });
      $buttons(btns);
    }
  }, [webbuttonConfig, showDraft, showWithdraw, showIsUrge, inbiz, hiddenButtons, isEditor, initialTaskState, isNewVersionDesigner, newActions]);

  useEffect(() => {
    if (inbiz && inbiz?.workFlow && (inbiz?.workFlow?.ccMember || inbiz?.workFlow?.baseInfo?.ccMember)) {
      if (isNewVersionDesigner) {
        const _ccMember = inbiz?.workFlow?.baseInfo?.ccMember ? JSON.parse(inbiz?.workFlow?.baseInfo?.ccMember) : [];
        const arr = _ccMember.map((item: { name: any; }) => {
          return {
            ...item,
            Name: item?.name,
          }
        });
        $selected(arr);
      } else {
        const arr = JSON.parse(inbiz?.workFlow?.ccMember).map((item: { text: any; }) => {
          return {
            ...item,
            Name: item?.text
          }
        });
        $selected(arr);
      }
    }
  }, [inbiz, isNewVersionDesigner]);

  const buttonStyle = {
    height: 40,
    color: '#fff',
    background: 'var(--inbiz-color-primary)',
    padding: '0 15px',
  };

  return (
    <BizBody {...props}>
      <div className="inbiz-ProcessButton">
        {buttonVisible == 'visible' && !batchApproval && (
          <>
            {(isEditor || tabKey == '2') &&
              buttons.length > 0 &&
              (showComment || showComment == undefined) && (
                <div className="inbizTextArea">
                  <TextArea
                    value={opinions}
                    onChange={(e) => $opinions(e.target.value)}
                    placeholder={tips ? getMessage(tips) : getMessage('processButton.tipsContent')}
                    style={{ width: 550, height: 140 }}
                    maxLength={163}
                    autoSize={false}
                  />
                </div>
              )}
            {inbiz &&
              inbiz?.workFlow &&
              (inbiz?.workFlow?.activityNo !== 'firstTask' || inbiz?.workFlow?.baseInfo?.activityNo !== 'firstTask') &&
              taskState != 130 &&
              (inbiz?.workFlow?.activityNo !== 'sign' || inbiz?.workFlow?.baseInfo?.activityNo !== 'sign') &&
              tabKey == '2' &&
              buttons.length > 0 &&
              (showCCmember || showCCmember == undefined) && (
                <div className="sendToPeople">
                  <div className="sendContainer">
                    <div className="sendTitle">
                      <InbizIcon
                        type="icon-ic-add"
                        style={{ color: 'var(--inbiz-color-primary)', marginRight: 5 }}
                      />
                      <span
                        onClick={() => {
                          if (inbiz?.workFlow?.ccMember || inbiz?.workFlow?.baseInfo?.ccMember) {
                            return;
                          };
                          $memberSelectVisible(true)
                        }}
                        style={{ color: 'var(--inbiz-color-primary)' }}
                      >
                        <TextWidget>processButton.sendTo</TextWidget>:
                      </span>
                    </div>
                    <AutoInput
                      inbiz={inbiz}
                      $selected={$selected}
                      selected={selected}
                      bordered={false}
                      width={470}
                      showArrow={false}
                      disabled={inbiz?.workFlow?.ccMember || inbiz?.workFlow?.baseInfo?.ccMember}
                    />
                  </div>
                </div>
              )}
            <div className="buttonList">
              {buttons.map((item: ButtonStructure, index: number) => {
                if (item?.action == 'returnsBack') {
                  return (
                    //visible={returnBackVisible}
                    <Dropdown overlay={isEditor ? <span /> : returnMenu} arrow={false}>
                      <Button
                        // onMouseOver={() => {
                        //   if (isEditor) {
                        //     return false;
                        //   }
                        //   $returnBackVisible(true);
                        // }}
                        // onMouseLeave={() => {
                        //   if (isEditor) {
                        //     return false;
                        //   }
                        //   $returnBackVisible(false);
                        // }}
                        type="primary"
                        style={{
                          ...buttonStyle,
                          background:
                            item.bgColor && !item.bgColor.includes('undefined')
                              ? item.bgColor
                              : 'var(--inbiz-color-primary)',
                          color:
                            item.fontColor && !item.fontColor.includes('undefined')
                              ? item.fontColor
                              : '#fff',
                        }}
                      >
                        <TextWidget>{item.name}</TextWidget>
                      </Button>
                    </Dropdown>
                  );
                }
                if (item?.action == 'plusSign') {
                  return (
                    <Button
                      type="primary"
                      onClick={() => {
                        if (isEditor) {
                          return false;
                        }
                        $plusSignVisible(true);
                      }}
                      style={{
                        ...buttonStyle,
                        background:
                          item.bgColor && !item.bgColor.includes('undefined')
                            ? item.bgColor
                            : 'var(--inbiz-color-primary)',
                        color:
                          item.fontColor && !item.fontColor.includes('undefined')
                            ? item.fontColor
                            : '#fff',
                      }}
                    >
                      <TextWidget>{item.name}</TextWidget>
                    </Button>
                  );
                }
                if (item?.action == 'assign') {
                  return (
                    <Button
                      type="primary"
                      onClick={() => {
                        if (isEditor) {
                          return false;
                        }
                        setAssignVisible(true);
                      }}
                      style={{
                        ...buttonStyle,
                        background:
                          item.bgColor && !item.bgColor.includes('undefined')
                            ? item.bgColor
                            : 'var(--inbiz-color-primary)',
                        color:
                          item.fontColor && !item.fontColor.includes('undefined')
                            ? item.fontColor
                            : '#fff',
                      }}
                    >
                      <TextWidget>{item.name}</TextWidget>
                    </Button>
                  );
                }
                return (
                  <Button
                    style={{
                      ...buttonStyle,
                      background:
                        item.bgColor && !item.bgColor.includes('undefined')
                          ? item.bgColor
                          : 'var(--inbiz-color-primary)',
                      color:
                        item.fontColor && !item.fontColor.includes('undefined')
                          ? item.fontColor
                          : '#fff',
                    }}
                    key={index}
                    onClick={() => {
                      handleClick({
                        item,
                        events,
                        inbiz,
                        operationSuccess,
                        selected,
                        mySummary,
                        taskId,
                        opinions,
                        props,
                        instanceId,
                        taskState,
                        processvars,
                        processId,
                        $terminateVisible,
                        $withDrawVisible,
                        userInfo,
                        id,
                        formId,
                        drafID,
                        pageId,
                      })
                    }
                    }
                  >
                    <TextWidget>{item.name}</TextWidget>
                  </Button>
                );
              })}
            </div>
          </>
        )}
        <MemberSelect
          visible={memberSelectVisible}
          config={{
            pageSize: 10,
            multiple: true,
            tabs: ['user'],
            selected: selected,
            onOk: (keys, selectedpeople, map) => {

              if (selectedpeople.length < 1) {
                $selected([]);
                $memberSelectVisible(false);
                return;
              }

              if (selectedpeople.length > 10) {
                return message.warn(getMessage('processButton.topsCCmember'));
              }

              const arr = [...selected, ...selectedpeople].reduce((item, next) => {
                const index = item.find((ele: { identityid: any; }) => ele.identityid == next.identityid);
                if (!index) {
                  item.push(next);
                }
                return item;
              }, []);
              $selected(arr);
              $memberSelectVisible(false);

            },
            onCancel: () => {
              // $selected([]);
              $memberSelectVisible(false);
            },
          }}
        />
        {
          assignVisible
          &&
          <MemberSelect
            visible={assignVisible}
            config={{
              pageSize: 10,
              multiple: false,
              tabs: ['user'],
              selected: [],
              onOk: async (keys, selectedpeople, map) => {
                if (selectedpeople.length < 1) {
                  message.warn(getMessage('processButton.chooseAssignPeople'));
                  return;
                };
                const params = {
                  delegateUserId: selectedpeople.map((item) => item.id).join(','),
                  handelUserId: userInfo.ID,
                  taskIds: taskId,
                };
                inbiz?.submit?.(true).then(() => {
                  assignTask(params).then((res) => {
                    operationSuccess(res, getMessage('processButton.assign'), 'assign');
                    setAssignVisible(false);
                  });
                });
              },
              onCancel: () => {
                // $selected([]);
                setAssignVisible(false);
              },
            }}
          />
        }
        {/**终止流程弹窗 */}
        <TerminateModal
          visible={terminateVisible}
          $visible={$terminateVisible}
          instanceId={instanceId}
          inbiz={inbiz}
          operationSuccess={operationSuccess}
          taskId={taskId}
          opinions={opinions}
          mySummary={mySummary}
        />
        {/**终止撤回弹窗 */}
        <WithDrawModal
          visible={withDrawVisible}
          $visible={$withDrawVisible}
          instanceId={instanceId}
          operationSuccess={operationSuccess}
          inbiz={inbiz}
        />
        {/**加签弹窗 */}
        <PlusSign
          visible={plusSignVisible}
          $visible={$plusSignVisible}
          taskId={taskId}
          operationSuccess={operationSuccess}
          inbiz={inbiz}
          opinions={opinions}
          mySummary={mySummary}
          isNewVersionDesigner={isNewVersionDesigner}
        />
      </div>
    </BizBody>
  );
});

export default App;
export { App as ProcessButton };
